<script setup lang="ts">
import { onBeforeRouteLeave, onBeforeRouteUpdate } from "vue-router";
import { useRouter } from "vue-router";
const router = useRouter();
const changeId = () => {
  router.push({
    path: "/permission",
    query: {
      id: "233",
    },
  });
};

// 与 beforeRouteUpdate 相同，无法访问 `this`
onBeforeRouteUpdate(async (to, from) => {
  // 仅当 id 更改时才获取用户，例如仅 query 或 hash 值已更改
  if (to.query.id !== from.query.id) {
    const answer = window.confirm("切换id，会丢失当前没保存的信息哦!");
    // 取消导航并停留在同一页面上
    if (!answer) return false;
    return true;
  }
});

// 与 beforeRouteLeave 相同，无法访问 `this`
onBeforeRouteLeave((to, from) => {
  console.log("离开当前页面", to, from);
  const answer = window.confirm("离开当前页面会丢失当前没保存的信息哦!");
  // 取消导航并停留在同一页面上
  if (!answer) return false;
});
</script>
<template>
  <h1>当前页面：{{ $route.query.id }}</h1>
  <button @click="changeId">换页面id</button>
</template>
